//
//  BRHomeTopView.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/29.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRHomeTopView.h"
#import "BRFAQSubTableViewCell.h"

#import "Lottie-Swift.h"

#define kTop_h (154.0 + 32)
#define kView_h (kScreenHeight - (169))

@interface BRHomeTopView ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    QMUILabel *_pbLB;
    QMUILabel *_timeLB;
    QMUILabel *_estimatedLB;
    UIImageView *_rightImage;
    CGFloat _view_h;
    UIView *_conteView;
    UIView *_lineView;
    UIView *_shadowView;
}

@property (nonatomic,strong) NSArray *datas;

@property (nonatomic,strong) QMUITableView *tableView;

@property (nonatomic,strong) CompatibleAnimationView *lottieView;

@end

@implementation BRHomeTopView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _view_h = kTop_h;
        [self setUI];
//        [self createShadow];
    }
    return self;
}

- (void)dealloc
{
    [self.lottieView stop];
}

- (void)start:(NSInteger)time {
    
    if (!self.timer.isValid) {
        WS(weakSelf);
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            weakSelf.time = time;
        }];
        
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
}

- (void)setTime:(NSInteger)time {
    _time = time;
//    NSString *timeS = [BRTools rentingTime:[NSString stringWithFormat:@"%ld",time]];
    NSString *timeS = [BRTools getDuringTimeFromTimestamp:[NSString stringWithFormat:@"%ld",time] formatter:@"yyyy年MM月dd日 HH:mm:ss"];
    _timeLB.text = [NSString stringWithFormat:@"%@: %@",Localized(@"home_duration"),timeS];
//    NSLog(@"timer run");
//    NSString *timeBlockStr = [BRTools getDuringTimeFromTimestamp:[NSString stringWithFormat:@"%ld",time] formatter:@"yyyy年MM月dd日 HH:mm:ss"];
    if (self.timerBlock) self.timerBlock(timeS);
}

- (void)show {
    self.hidden = NO;
    
}

- (void)hidden {
    self.isOpen = NO; //同时收起FAQ
    _timeLB.text = [NSString stringWithFormat:@"%@: 00:00:00",Localized(@"home_duration")];
    if (self.timerBlock) self.timerBlock(@"00:00:00.00");
//    self.hidden = YES;
//    NSLog(@"_timeLB hidden");
//    [self.lottieView stop];
}

- (void)cancleTimer {
    
    if (self.timer.isValid) {

        [self.timer invalidate];
//        NSLog(@"timer cancle");

    }
}

- (void)toDetail {
    if (self.detailClick) {
        self.detailClick();
    }
}

- (void)openFAQ {
    
    self.isOpen = !self.isOpen;
}

- (void)openView {
    if (self.openDoBlock) {
        self.openDoBlock();
    }
    self.isOpen = !self.isOpen;
}

- (void)setIsOpen:(BOOL)isOpen {
    _isOpen = isOpen;
    _shadowView.hidden = !isOpen;
    _lineView.hidden = !isOpen;
    if (isOpen) {
        _view_h = kTop_h + self.tableView.contentSize.height;
        self.mj_h = kView_h;
        [UIView animateWithDuration:0.25 animations:^{
            
            self->_rightImage.transform = CGAffineTransformMakeRotation(M_PI_2);
            self->_conteView.mj_h = self->_view_h;
        } completion:^(BOOL finished) {
            
        }];
        
    }else {
        _view_h = kTop_h;
        [UIView animateWithDuration:0.25 animations:^{
            self->_rightImage.transform = CGAffineTransformMakeRotation(0);
            self->_conteView.mj_h = self->_view_h;;
        } completion:^(BOOL finished) {
            
        }];
        self.mj_h = _view_h + 18 + KStatusBarHeight;
    }
//    self.mj_h = _view_h;
//    [_conteView layoutSubviews];
    if (self.openBlock) {
        self.openBlock(isOpen);
    }
}


- (NSArray *)datas {
    
    return @[Localized(@"home_orderErrText1"),Localized(@"home_orderErrText2"),Localized(@"home_orderErrText3"),Localized(@"home_orderErrText4"),Localized(@"menu_helpCentre")];
}

- (void)setPbIDStr:(NSString *)pbIDStr {
    _pbIDStr = pbIDStr;
    pbIDStr = pbIDStr.length == 0 ? @"--" : pbIDStr;
    _pbLB.text = [NSString stringWithFormat:@"%@: %@",Localized(@"order_pbID"),pbIDStr];
}

- (void)setEstimatedStr:(NSString *)estimatedStr {
    _estimatedStr = estimatedStr;
    _estimatedLB.text = [NSString stringWithFormat:@"%@: %@",Localized(@"home_estimatedFees"),estimatedStr];
}

#pragma mark - delegate --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.datas.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    BRFAQSubTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"BRFAQSubTableViewCell"];

    cell.textL.text = self.datas[indexPath.row];
    if (indexPath.row == self.datas.count - 1) {
        cell.lineV.hidden = YES;
    }else {
        cell.lineV.hidden = NO;
    }
    [cell.textL sizeToFit];
    [cell layoutSubviews];
    
    cell.dotView.backgroundColor = kColorMain;
    cell.textL.textColor = UIColor.qd_titleTextColor2;
    cell.contentView.backgroundColor = UIColor.whiteColor;
    cell.lineV.backgroundColor = UIColorMakeWithHex(@"#D2D8E2");
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cel_h  = 0;

    NSString *string = self.datas[indexPath.row];
    cel_h = [string jk_heightWithFont:[UIFont br_fontM:14] constrainedToWidth:kScreenWidth - 110.] + 27.;
    return  cel_h;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.faqClick) {
        self.faqClick(indexPath.row);
    }
}

#pragma mark - SET UI --
- (void)setUI {
    self.backgroundColor = UIColorClear;
//    self.userInteractionEnabled = YES;
    UIColor *bgColor = UIColor.whiteColor;
    UIColor *bgLineColor = UIColorMakeWithHex(@"#D2D8E2");
    //用于遮罩顶部圆角
//    UIView *toView = [[UIView alloc] initWithFrame:CGRectMake(16, 0, kScreenWidth - 32, 40)];
//    toView.backgroundColor = bgColor;
//    [self addSubview:toView];
    
    
    UIView *shadowV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.mj_w, kView_h)];
    shadowV.userInteractionEnabled = YES;
    shadowV.backgroundColor = UIColorClear;
    [self addSubview:shadowV];
    shadowV.hidden = YES;
    _shadowView = shadowV;
    UITapGestureRecognizer *sTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openFAQ)];
    [shadowV addGestureRecognizer:sTap];
    
    //CGRectMake(28, 18 + KStatusBarHeight, kScreenWidth - 56, 144)
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(16, 0, kScreenWidth - 32, kView_h)];
    view.backgroundColor = bgColor;
    view.layer.cornerRadius = 13;
    view.layer.masksToBounds = YES;
    view.userInteractionEnabled = YES;
    [self addSubview:view];
    _conteView = view;
    
    UIControl *detailBtn = [[UIControl alloc] initWithFrame:CGRectMake(0, 10, view.mj_w, 60)];
    [view addSubview:detailBtn];
    [detailBtn addTarget:self action:@selector(toDetail) forControlEvents:UIControlEventTouchUpInside];
    
    UIControl *openBtn = [[UIControl alloc] initWithFrame:CGRectMake(0, 70, view.mj_w, 84)];
    [view addSubview:openBtn];
    [openBtn addTarget:self action:@selector(openView) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *lineV2 = [[UIView alloc] initWithFrame:CGRectMake(0, 69.5, view.mj_w, 0.5)];
    lineV2.backgroundColor = bgLineColor;
    [view addSubview:lineV2];
    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, kTop_h - 0.5, view.mj_w, 0.5)];
    lineV.backgroundColor = bgLineColor;
    lineV.hidden = YES;
    [view addSubview:lineV];
    _lineView  = lineV;
    
    UIImageView *topMoreImg = [[UIImageView alloc] init];
    topMoreImg.image = UIImageMake(@"arrow_right_gray46");
    [detailBtn addSubview:topMoreImg];
    [topMoreImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(46);
        make.height.mas_equalTo(46);
        make.top.offset(8);
        make.right.equalTo(view);
    }];
    
    
    //----------------------------
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.alignment = UIStackViewAlignmentFill;
    stackView.distribution = UIStackViewDistributionFillEqually;
    stackView.spacing = 14;
    stackView.userInteractionEnabled = NO;
    [view addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(view.mas_right).offset(-50);
        make.left.equalTo(view.mas_left).offset(16);
//        make.height.mas_equalTo(64);
        make.top.equalTo(view.mas_top).offset(84);
    }];
    
    _pbLB = [BRToolsView br_label:@"" textColor:UIColor.qd_titleTextColor2 font:[UIFont br_fontM:14]];
    
    QMUILabel *timeLB = [[QMUILabel alloc] init];
    timeLB.text = [NSString stringWithFormat:@"%@: %@",Localized(@"home_duration"),[BRTools getChargingTime:0]];
    timeLB.textColor = UIColor.qd_titleTextColor2;
    timeLB.font = [UIFont br_fontM:14];
    timeLB.textAlignment = NSTextAlignmentLeft;
    _timeLB = timeLB;
    
    QMUILabel *estimatedLB = [[QMUILabel alloc] init];
    estimatedLB.text = [NSString stringWithFormat:@"%@: %@ --",Localized(@"home_estimatedFees"),USERManager.currency.uppercaseString];
    estimatedLB.textColor = UIColor.qd_titleTextColor2;
    estimatedLB.font = [UIFont br_fontM:14];
    estimatedLB.textAlignment = NSTextAlignmentLeft;
    _estimatedLB = estimatedLB;
    
    [stackView addArrangedSubview:_pbLB];
    [stackView addArrangedSubview:timeLB];
    [stackView addArrangedSubview:estimatedLB];
    //----------------------------
    UIImageView *image = [[UIImageView alloc] init];
    image.image = UIImageMake(@"arrow_right_gray46");
    [openBtn addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(46);
        make.height.mas_equalTo(46);
        make.centerY.equalTo(timeLB.mas_centerY).offset(0);
        make.right.equalTo(view);
    }];
    _rightImage = image;
    
    UIImageView *faqHelpImg = [[UIImageView alloc] init];
    faqHelpImg.image = UIImageMake(@"home_help");
    [openBtn addSubview:faqHelpImg];
    [faqHelpImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(28);
        make.centerY.equalTo(image);
        make.right.equalTo(image.mas_left).offset(-4);
    }];
    //----------------------------
//    UIImageView *chargImg = [[UIImageView alloc] init];
//    chargImg.image = UIImageMake(@"home_charging");
    [detailBtn addSubview:self.lottieView];
    [self.lottieView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(50);
        make.centerY.equalTo(detailBtn);
        make.left.equalTo(detailBtn).offset(5);
    }];
    
    
    QMUILabel *statusLabel = [[QMUILabel alloc] init];
    statusLabel.text = Localized(@"home_nowCharging");
    statusLabel.textColor = UIColor.qd_titleTextColor;
    statusLabel.font = [UIFont br_fontB:17];
    statusLabel.numberOfLines = 2;
    statusLabel.textAlignment = NSTextAlignmentLeft;
    [detailBtn addSubview:statusLabel];
    [statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(detailBtn);
        make.left.equalTo(view).offset(52);
//        make.right.equalTo(timeLB.mas_left).offset(0);
    }];
    //----------------------------
    self.tableView.estimatedRowHeight = 44;
    self.tableView.bounces = NO;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRFAQSubTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRFAQSubTableViewCell"];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).offset(kTop_h);
        make.left.bottom.right.equalTo(view);
    }];
    
    [self.tableView reloadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.lottieView play];
    });
    
}

- (QMUITableView *)tableView{
    if (!_tableView) {
        _tableView = [[QMUITableView alloc]initWithFrame:CGRectMake(0,60, self.mj_w, kScreenHeight - kSafeAreaTopHeight) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = kColorBGEB;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _tableView;
}

- (CompatibleAnimationView *)lottieView {
    
    if (_lottieView == nil) {
        NSString *patch = [BRThemeManage br_patchStr:@"Charging3" type:@"json"];
        _lottieView = [[CompatibleAnimationView alloc] initWithUrl:[NSURL fileURLWithPath:patch]];
        _lottieView.frame = CGRectMake(0, 0, 28, 28);
        _lottieView.loopAnimationCount = -1;
    }
    return _lottieView;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code

}

- (void)createShadow {
    self.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.07].CGColor;
    self.layer.shadowOffset = CGSizeMake(0,5);
    self.layer.shadowOpacity = 1;
    self.layer.shadowRadius = 8;
}


@end
